package com.factory.iamp.controller;

import com.factory.iamp.pojo.GroupBuild;
import com.factory.iamp.pojo.User;
import com.factory.iamp.service.GroupService;
import com.factory.iamp.utils.helper.PageHelper;
import com.factory.iamp.utils.token.LoginToken;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

@RestController
@RequestMapping("/group")
@Validated
public class GroupController {
    @Resource
    private GroupService groupService;

    @GetMapping("/list/{limit}/{page}")
    @LoginToken
    public PageHelper getAllGroup(@PathVariable("limit") int limit, @PathVariable("page") int page) {
        PageHelper result = new PageHelper(groupService.Count(), page, limit);
        result.setData(groupService.ListPaged(result));
        return result;
    }

    @GetMapping("/{gid}/member/{limit}/{page}")
    @LoginToken
    public PageHelper getGroupMember(
            @PathVariable("gid") int gid,
            @PathVariable("limit") int limit,
            @PathVariable("page") int page
    ) {
        PageHelper result = new PageHelper(groupService.groupMemberCount(gid), page, limit);
        result.setData(groupService.groupMemberListPaged(result, gid));
        return result;
    }

    @GetMapping("/find/name/{limit}/{page}")
    @LoginToken
    public PageHelper findGroupByName(
            @PathVariable("limit") int limit,
            @PathVariable("page") int page,
            @RequestParam("name") String name
    ) {
        name += "%";
        PageHelper result = new PageHelper(groupService.findByNameCount(name), page, limit);
        result.setData(groupService.findByNameListPaged(result, name));
        return result;
    }

    @PostMapping("/make")
    @LoginToken(checkPrivate = true)
    public void makeGroup(@RequestBody @Valid GroupBuild groupBuild) {
        groupService.makeGroup(groupBuild.getName(), groupBuild.getMember());
    }

    @PostMapping("/alter/{gid}")
    @LoginToken(checkPrivate = true)
    public void alterGroup(@RequestBody @Valid GroupBuild groupBuild, @PathVariable("gid") int gid) {
        groupService.alterGroup(gid, groupBuild.getMember());
    }

    @PostMapping("/join/{gid}")
    @LoginToken
    public void joinGroup(@RequestAttribute("iampUser") User user, @PathVariable("gid") int gid) {
        groupService.joinGroup(user.getUid(), gid);
    }

    @DeleteMapping("/{gid}")
    @LoginToken(checkPrivate = true)
    public void deleteGroup(@PathVariable("gid") int gid) {
        groupService.deleteGroup(gid);
    }
}
